

package de.jeeyeon;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import de.jeeyeon.util.EmoKeyboard;



public class AddActivity extends Activity 
{
	
//	private Button button; //load pictures button
	private Button button2; //send entry button
	
	private ImageView imgView;
	private ImageView imgView2;
	private ImageView imgView3;
	private EditText textarea;
	
	private Button emobutton;
	
	private String selectedImagePath;
	
	private String author;
	
	private static int SELECT_PICTURE = 1;
	
	public static final String URL = "http://snuk87.sn.funpic.de/add_entry.php";
	
	private EmoKeyboard emoKeyboard;
	
	

	
	private int counter = 0;

	@Override
	protected void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_add);

		
		
		
		Bundle extras = getIntent().getExtras();
		author = extras.getString("author");
				
//		imgView = (ImageView) findViewById(R.id.imgView);
//		imgView2 = (ImageView) findViewById(R.id.imgView2);
//		imgView3 = (ImageView) findViewById(R.id.imgView3);		
		textarea = (EditText) findViewById(R.id.textfield_entry);
		setKeyboardListener();

		
		emoKeyboard = new EmoKeyboard(this, R.id.keyboardview, R.xml.emo, textarea);
		
//		button = (Button) findViewById(R.id.addpictures_button);
//		setLoadPicturesButtonListener();

		button2 = (Button) findViewById(R.id.send_button);
		setSendButtonListener();
		
		emobutton = (Button) findViewById(R.id.emoBtn);
		setEmoButtonListener();
		registerForContextMenu(emobutton);
	}
	
	@Override public void onBackPressed() 
	{
	    if( emoKeyboard.isCustomKeyboardVisible() ) emoKeyboard.hideCustomKeyboard(); else this.finish();
	}

	
	private void setKeyboardListener()
	{
		textarea.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v)
			{
				emoKeyboard.hideCustomKeyboard();
				
			}
		});
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) 
	{
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.add, menu);
		return true;
	}
	
	private void setEmoButtonListener()
	{
		emobutton.setOnClickListener(new OnClickListener() 
		{	
			@Override
			public void onClick(View v) 
			{	
				emoKeyboard.showCustomKeyboard(v);
			}
		});
	}
	
//	private void setLoadPicturesButtonListener()
//	{
//		button.setOnClickListener(new OnClickListener()
//		{
//			
//			@Override
//			public void onClick(View v) 
//			{
//				Intent i = new Intent();
//				i.setType("image/*");
//				i.setAction(Intent.ACTION_GET_CONTENT);
//				startActivityForResult(Intent.createChooser(i, "Select Picture"), SELECT_PICTURE);
//				
//			}
//		});
//	}
	
	private void setSendButtonListener()
	{
		button2.setOnClickListener(new OnClickListener() 
		{
			@Override
			public void onClick(View arg0) 
			{
				new AsyncTask<String, Void, String>() 
				{
					@Override
					protected String doInBackground(String... params) 
					{
						String output = null;
						try
						{
							String text = textarea.getText().toString();
							
							DefaultHttpClient client = new DefaultHttpClient();
							HttpPost post = new HttpPost(URL);
							
					        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
					        nameValuePairs.add(new BasicNameValuePair("entry", text));
					        nameValuePairs.add(new BasicNameValuePair("date", getDate()));
					        nameValuePairs.add(new BasicNameValuePair("author", author));
					        post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
					        
					        HttpResponse response = client.execute(post);
					        HttpEntity entity = response.getEntity();
					        output = EntityUtils.toString(entity);
					     }
						catch(Exception e){ e.printStackTrace(); Log.d("Catch: " + e.toString(), "jeejee"); }
						
						return output;
					}
					
					protected void onPostExecute(String result)
					{
						Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();
						createNotification();
						finish();
					}
				}.execute();
			}
		});
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		
		if(resultCode == RESULT_OK)
		{
			if(requestCode == SELECT_PICTURE)
			{
				Uri selectedImage = data.getData();
				selectedImagePath = getPath(selectedImage);
				
				Bitmap bm = getImageBitmap(selectedImagePath);
				
				switch(counter)
				{
					case 0: imgView.setImageBitmap(bm); counter++;break;
					case 1: imgView2.setImageBitmap(bm); counter++;break;
					case 2: imgView3.setImageBitmap(bm); counter++;break;
					default: break;
				}
			}
		}

	}
	
	public String getPath(Uri uri)
	{
		String[] filePathColumn = { MediaStore.Images.Media.DATA };
		Cursor cursor = getContentResolver().query(uri, filePathColumn, null, null, null);
		
		int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
		cursor.moveToFirst();
		
		return cursor.getString(column_index);
	}
	


	private Bitmap getImageBitmap(String url) 
	{

		Options dimensionOptions = new Options();
		dimensionOptions.inJustDecodeBounds = true;

		BitmapFactory.decodeFile(url, dimensionOptions);

		int rawWidth = dimensionOptions.outWidth;
		int targetWidth = 480;

		float sampleSize = (float) rawWidth / (float) targetWidth;
		int sample = (int) Math.floor(sampleSize);

		Options scaleOptions = new Options();
		scaleOptions.inPreferredConfig = Bitmap.Config.ARGB_8888;
		scaleOptions.inSampleSize = sample;

		Bitmap scaled = BitmapFactory.decodeFile(url, scaleOptions);

		return scaled;
	}
	
	private String getDate()
	{
		Date date = new Date();
		SimpleDateFormat df = new SimpleDateFormat( "dd-MM-yyyy", Locale.GERMANY);
		String datestring = df.format(date);
		
		return datestring;
	}
	
	private void createNotification()
	{	
		//add GCM
		
		Intent intent = new Intent(this, MainActivity.class);
		PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, 0);
		
		Notification noti = new Notification.Builder(this)
				.setContentTitle("Diary")
				.setContentText("there is a new entry in ur diary").setSmallIcon(R.drawable.ic_launcher2)
				.setContentIntent(pIntent)
				.addAction(R.drawable.ic_launcher2, "Read", pIntent).build();
		
		NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		noti.flags |= Notification.FLAG_AUTO_CANCEL;
		notificationManager.notify(0, noti);	
	}
}
